package app.biz.service.impl;

import app.biz.model.EcgRequest;
import app.biz.service.atom.EcgCoreFetcher;
import app.biz.service.atom.LBService;
import app.framework.component.HttpClienter;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 基于Spring RestTemplate实现的ECG服务远程结果获取接口
 * */
@Primary // 同时有多个impl实现同一接口，且引用时未声明@Qulifier时需要指定
@Service("RestTemplate")
public class EcgCoreFetcherImpl implements EcgCoreFetcher {
  private static final Logger logger = LoggerFactory.getLogger(EcgCoreFetcherImpl.class);

  @Value("${service.ecgai.url}")
  private String[] ecgaiUrl;

  private static String METHOD = "/ins/json";

  RestTemplate restTemplate = HttpClienter.getRestTemplate();

  private LBService lbService;

  @Autowired  void initLBService(){
        lbService = new LBServiceSimpleImpl();
        logger.info("初始化负载均衡服务");
        lbService.load(ecgaiUrl);
  }

  @Override
  public JSONObject fetchResult(EcgRequest ecgRequest) {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString());
    HttpEntity<String> httpEntity = new HttpEntity<>(toBody(ecgRequest), headers);
    String targetUrl = lbService.get();
    logger.info("Target URL:{}",targetUrl);
    String result =  restTemplate.postForObject(targetUrl + METHOD,httpEntity,String.class);
    return JSONObject.parseObject(result);
  }

    private String toBody(EcgRequest request){
        return "xmldata="
                + request.getXmlData()
                + "&fs="
                + request.getFs()
                + "&device_id="
                + request.getDevice_id()
                + "&leads="
                + request.getLeads();
  }
}
